package com.sntk.organauthomanager.application.mapper;

import com.sntk.organauthomanager.application.dto.RoleDTO;
import com.sntk.organauthomanager.application.dto.RoleVO;
import com.sntk.organauthomanager.infrastructure.db.entity.OrganizationEntity;
import com.sntk.organauthomanager.infrastructure.db.entity.RoleEntity;
import com.sntk.organauthomanager.infrastructure.db.entity.UserEntity;
import com.sntk.organauthomanager.infrastructure.db.repository.OrganizationDBRepository;
import com.sntk.organauthomanager.infrastructure.db.repository.UserDBRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @ClassName: RoleMapper
 * @author: wgchao
 * @createTime: 2020/7/21 4:01 PM
 * @Description: TODO
 */
@Component
public class RoleMapper {
    @Autowired
    private OrganizationDBRepository organizationDBRepository;
    @Autowired
    private UserDBRepository userDBRepository;

    public RoleDTO transformToDTO(RoleEntity roleEntity){
        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(roleEntity, roleDTO);
        return roleDTO;
    }

    public RoleVO transformToVO(RoleEntity roleEntity){
        RoleVO roleVO = new RoleVO();
        BeanUtils.copyProperties(roleEntity, roleVO);
        if(!StringUtils.isEmpty(roleEntity.getInstitutionNumber())){
            OrganizationEntity organization = organizationDBRepository.findFirstByInstitutionNumberAndDelFalse(roleEntity.getInstitutionNumber());
            if(organization != null){
                roleVO.setInstitutionName(organization.getInstitutionName());
            }
        }
        if(!StringUtils.isEmpty(roleEntity.getCreator())){
            UserEntity creator = userDBRepository.findFirstByUnameAndDelFalse(roleEntity.getCreator());
            if(creator != null){
                roleVO.setCreatorName(creator.getUserName());
            }
        }
        if(!StringUtils.isEmpty(roleEntity.getLastUpdator())){
            UserEntity updator = userDBRepository.findFirstByUnameAndDelFalse(roleEntity.getLastUpdator());
            if(updator != null){
                roleVO.setLastUpdatorName(updator.getUserName());
            }
        }

        return roleVO;
    }
}
